package com.dz.controller;

import com.dz.annotation.OperationLog;
import com.dz.bean.Guide;
import com.dz.bean.Visitor;
import com.dz.service.GuideService;
import com.dz.service.VisitorService;
import com.dz.util.EmailUtil;
import com.dz.util.PasswordUtil;
import com.dz.util.Result;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/register")
public class RegisterController {// 注册

    @Autowired
    private VisitorService visitorService;

    @Autowired
    private GuideService guideService;

    // 临时存储邮箱验证码（实际项目中应该使用Redis等）
    private static final Map<String, String> emailCodeCache = new ConcurrentHashMap<>();// key:邮箱 value:验证码
    private static final Map<String, Long> codeTimeCache = new ConcurrentHashMap<>();// key:邮箱 value:发送时间

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/sendEmailCode")
    public Result sendEmailCode(@RequestBody Map<String, String> requestData) {
        try {
            String email = requestData.get("email");
            if (email == null || email.trim().isEmpty()) {
                return Result.error(500, "邮箱不能为空");
            }

            // 生成6位随机验证码
            String code = String.format("%06d", (int) (Math.random() * 1000000));//format: %06d: 填充6位，不足6位前面补0

            // 保存验证码和时间戳
            emailCodeCache.put(email, code);
            codeTimeCache.put(email, System.currentTimeMillis());

            // 调用邮件工具类发送邮件
            EmailUtil.sendEmail(email, code);

            return Result.success("验证码已发送至您的邮箱");
        } catch (MessagingException e) {
            log.error("发送验证码失败", e);
            return Result.error(500, "发送验证码失败，请检查邮箱地址是否正确");
        } catch (Exception e) {
            log.error("发送验证码失败", e);
            return Result.error(500, "发送验证码失败: " + e.getMessage());
        }
    }

    /**
     * 游客注册
     */
    @PostMapping("/visitor")
    @OperationLog("游客注册")
    public Result registerVisitor(@RequestBody Map<String, String> requestData) {
        try {
            String username = requestData.get("username");
            String phone = requestData.get("phone");
            String email = requestData.get("email");
            String emailCode = requestData.get("emailCode");
            String password = requestData.get("password");

            // 参数校验
            if (username == null || username.trim().isEmpty()) {
                return Result.error(500, "用户名不能为空");
            }

            if (phone == null || phone.trim().isEmpty()) {
                return Result.error(500, "手机号不能为空");
            }

            if (email == null || email.trim().isEmpty()) {
                return Result.error(500, "邮箱不能为空");
            }

            if (emailCode == null || emailCode.trim().isEmpty()) {
                return Result.error(500, "邮箱验证码不能为空");
            }

            if (password == null || password.trim().isEmpty()) {
                return Result.error(500, "密码不能为空");
            }

            // 验证邮箱验证码
            if (!validateEmailCode(email, emailCode)) {
                return Result.error(500, "邮箱验证码错误或已过期");
            }

            // 检查用户名是否已存在
            if (visitorService.getByUsername(username) != null) {
                return Result.error(500, "用户名已存在");
            }

            // 检查手机号是否已存在
            if (visitorService.getByPhone(phone) != null) {
                return Result.error(500, "手机号已被注册");
            }

            // 创建游客对象
            Visitor visitor = new Visitor();
            visitor.setUsername(username);
            visitor.setPhone(phone);
            visitor.setEmail(email);
            visitor.setGender(0); // 默认女性

            // 设置默认密码并加密
            //String defaultPassword = "123456"; // 默认密码
            visitor.setPassword(PasswordUtil.getEncryption(password));

            // 保存到数据库
            visitorService.add(visitor);

            // 清除验证码缓存
            clearEmailCode(email);

            return Result.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "注册失败: " + e.getMessage());
        }
    }

    /**
     * 地陪注册
     */
    @PostMapping("/guide")
    @OperationLog("地陪注册")
    public Result registerGuide(@RequestBody Map<String, String> requestData) {
        try {
            String username = requestData.get("username");
            String phone = requestData.get("phone");
            String email = requestData.get("email");
            String emailCode = requestData.get("emailCode");
            String password = requestData.get("password");

            // 参数校验
            if (username == null || username.trim().isEmpty()) {
                return Result.error(500, "用户名不能为空");
            }

            if (phone == null || phone.trim().isEmpty()) {
                return Result.error(500, "手机号不能为空");
            }

            if (email == null || email.trim().isEmpty()) {
                return Result.error(500, "邮箱不能为空");
            }

            if (emailCode == null || emailCode.trim().isEmpty()) {
                return Result.error(500, "邮箱验证码不能为空");
            }

            if (password == null || password.trim().isEmpty()) {
                return Result.error(500, "密码不能为空");
            }

            // 验证邮箱验证码
            if (!validateEmailCode(email, emailCode)) {
                return Result.error(500, "邮箱验证码错误或已过期");
            }

            // 检查用户名是否已存在
            if (guideService.getByUsername(username) != null) {
                return Result.error(500, "用户名已存在");
            }

            // 检查手机号是否已存在
            if (guideService.getByPhone(phone) != null) {
                return Result.error(500, "手机号已被注册");
            }

            // 创建地陪对象
            Guide guide = new Guide();
            guide.setUsername(username);
            guide.setPhone(phone);
            guide.setEmail(email);
            guide.setGender(0); // 默认女性
            guide.setPrice(0.0); // 默认价格

            // 设置默认密码并加密
            //String defaultPassword = "123456"; // 默认密码
            guide.setPassword(PasswordUtil.getEncryption(password));


            // 保存到数据库
            guideService.add(guide);

            // 清除验证码缓存
            clearEmailCode(email);

            return Result.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "注册失败: " + e.getMessage());
        }
    }

    /**
     * 验证邮箱验证码
     */
    private boolean validateEmailCode(String email, String code) {
        String cachedCode = emailCodeCache.get(email);
        Long codeTime = codeTimeCache.get(email);

        if (cachedCode == null || codeTime == null) {
            return false;
        }

        // 验证码3分钟内有效
        if (System.currentTimeMillis() - codeTime > 3 * 60 * 1000) {
            clearEmailCode(email);
            return false;
        }

        return cachedCode.equals(code);
    }

    /**
     * 清除邮箱验证码
     */
    private void clearEmailCode(String email) {
        emailCodeCache.remove(email);
        codeTimeCache.remove(email);
    }
}
